import EventManager from "./EventManager";

const { ccclass, property } = cc._decorator;

export enum ScreenDirection {
    Portrait, Landscape,
}

/** 务必手动勾上Canvas上的FitHeight和FitWidth,否则本类执行有误 */
@ccclass
export default class ScreenFit extends cc.Component {
    
    @property({ type: cc.Enum(ScreenDirection) })
    direction: ScreenDirection = ScreenDirection.Portrait;
    
    static readonly Event_OnFitted = 'Event_OnFitted';
    static isFitted = false;

    static get screenSize(): cc.Size {
        if (!ScreenFit.isFitted) {
            console.error('ScreenFit未初始化完成');
            return cc.Size.ZERO;
        }
        return cc.view.getDesignResolutionSize();
    }

    onDestroy(){
        ScreenFit.isFitted = false;
    }

    onLoad() {
        if (this.direction == ScreenDirection.Portrait) {
            cc.view.setOrientation(cc.macro.ORIENTATION_PORTRAIT);
        } else {
            cc.view.setOrientation(cc.macro.ORIENTATION_LANDSCAPE);
        }
        let canvas = cc.find("Canvas");
        this.checkSolution(canvas.width, canvas.height);
        ScreenFit.isFitted = true;
        console.log('ScreenFit初始化完成');
        EventManager.emit(ScreenFit.Event_OnFitted);
    }

    private checkSolution(designWidth: number, designHeight: number): void {
        let canvasSize = cc.view.getCanvasSize();
        let real_width = canvasSize.width,
            real_height = canvasSize.height,
            design_width = designWidth,
            design_height = designHeight;
        let scale_w_dr = design_width / real_width,
            scale_h_dr = design_height / real_height;

        if (scale_w_dr != scale_h_dr) {
            if (scale_w_dr > scale_h_dr) {
                let new_height = real_height * scale_w_dr;
                cc.view.setDesignResolutionSize(design_width, new_height, cc.ResolutionPolicy.SHOW_ALL);
            }
            else {
                let new_w = real_width * scale_h_dr;
                cc.view.setDesignResolutionSize(new_w, design_height, cc.ResolutionPolicy.SHOW_ALL);
            }
            cc.Canvas.instance.alignWithScreen();
            this.updateAllChildNodeWidget(cc.Canvas.instance.node);
        }
    }

    private updateAllChildNodeWidget(parentNode: cc.Node): void {
        if (parentNode == null) {
            return;
        }
        let widget = parentNode.getComponent(cc.Widget);
        if (widget != null) {
            widget.updateAlignment();
        }
        if (parentNode.childrenCount == 0) {
            return;
        }
        parentNode.children.forEach((childNode: cc.Node) => {
            this.updateAllChildNodeWidget(childNode);
        });
    }

}
